package ec.edu.ups.cidi.siia.plamdep.webcrawler.descarga;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.jsoup.Jsoup;

import ec.edu.ups.cidi.siia.plamdep.utils.Log;

public class HtmlUtils {
	private ArrayList<String> etiquetas = new ArrayList<String>();

	/**
	 * @param html
	 *            codigo el que se busca la etiqueta
	 * @param RGcomienza
	 *            //expresion regular de como empieza la etiqueta
	 * @param RGtermina
	 *            //expresion regular de como termina la etiqueta
	 * @param recursivo
	 *            //si envia true busca todas las etiquetas del mismo tipo si
	 *            envia false solo devuelve la primera etiqueta
	 * @param i
	 *            //este es solo de control siempre debe tener valor 0
	 */
	public  ArrayList<String> obtenerEtiqueta2(String html, String RGcomienza,
			String RGtermina, boolean recursivo, int i) {
		if (i == 0)
			etiquetas = new ArrayList<String>();
		Pattern p = Pattern.compile(RGcomienza);
		Matcher m = p.matcher(html);
		if (m.find()) 
		{
			html = html.substring(m.start(), html.length());
			Pattern p1 = Pattern.compile(RGtermina);
			Matcher m1 = p1.matcher(html);
			if (m1.find()) 
			{
				String li = html.substring(0, m1.end());
				etiquetas.add(li);
				html = html.substring(m1.end(), html.length());
				if (recursivo)
					this.obtenerEtiqueta2(html, RGcomienza, RGtermina,
							recursivo, 1);
			}
		}
		return etiquetas;
	}

	public String convertirToISO(String cadenaTexto) {

		Charset utf8charset = Charset.forName("UTF-8");
		Charset iso88591charset = Charset.forName("ISO-8859-15");
		// Decode UTF-8
		ByteBuffer bb = ByteBuffer.wrap(cadenaTexto.getBytes());
		CharBuffer data = utf8charset.decode(bb);
		// Encode ISO-8559-1
		ByteBuffer outputBuffer = iso88591charset.encode(data);
		byte[] outputData = outputBuffer.array();
		String datos = new String(outputData);

		return datos;
	}

	public String convertirToUTF8(String cadenaTexto) {

		Charset utf8charset = Charset.forName("UTF-8");
		Charset iso88591charset = Charset.forName("ISO-8859-15");
		// Decode UTF-8
		ByteBuffer bb = ByteBuffer.wrap(cadenaTexto.getBytes());
		CharBuffer data = iso88591charset.decode(bb);
		// Encode ISO-8559-1
		ByteBuffer outputBuffer = utf8charset.encode(data);
		byte[] outputData = outputBuffer.array();
		String datos = new String(outputData);

		return datos;
	}

	public boolean SaveFile(String FilePath, String FileContent,boolean CleanFileContent) {
		FileWriter file;
		BufferedWriter writer;
		try 
		{
			file = new FileWriter(FilePath, !CleanFileContent);
			writer = new BufferedWriter(file);
			writer.write(FileContent, 0, FileContent.length());

			writer.close();
			file.close();
			return true;
		} catch (Exception ex) 
		{
			Log.log(ex,Log.MOD_WEBCRAWLER,Log.LEVEL_ERROR, HtmlUtils.class,"error en SaveFile" );
			
		}
		return false;

	}
	public static String contentBetween(String html,String ini,String fin)
    {
		String htmlOriginal=html;
    	try{
    	
    		
    	int posi=html.indexOf(ini);
    	
    	if(posi<0||html.length()==0)return "";//controla que no se desborde
    	
    	html=html.substring(posi);
    	
		int f=html.indexOf(fin);
		
		html=html.substring(ini.length(),f);
    	}catch(Exception e)
    	{
    		Log.log(null,Log.MOD_WEBCRAWLER,Log.LEVEL_ERROR, HtmlUtils.class,"error en contentBetween"+htmlOriginal+"\nini:"+ini+"\nfin"+fin );
    		html="";
    	
    	}
		return html;
    }
	
	public static String htmlToText(String html)
	{
		html=html.replaceAll("</b>", "");
		html=Jsoup.parse(html).text();
		html=html.replaceAll("%3A", ":");
		html=html.replaceAll("%2F", "/");
		return html;
	}
	/**
	 * Metodo que sirve de parser para decodificar una url 
	 * codigos obtenidos en http://www.w3schools.com/tags/ref_urlencode.asp
	 * @return
	 */
	public static String decodeURL(String url)
	{
		
		try {
			url=java.net.URLDecoder.decode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return url;
	}
	
	/**
	 * Metodo que sirve de parser para codificar una url 
	 * codigos obtenidos en http://www.w3schools.com/tags/ref_urlencode.asp
	 * @return
	 */
	public static String encodeURL(String url)
	{
		
		try {
			url=java.net.URLEncoder.encode(url, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return url;
	}
	/**
     * Convierte un InputStream a un valor String
     */
    public static String getStringFromInputStream(InputStream is) {
		if(is==null)return "";
    	
    	BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		String line;
		try {
			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) 	sb.append(line);
		} catch (IOException e) 
		{
			Log.log(e,Log.MOD_WEBCRAWLER,Log.LEVEL_ERROR, DescargarFuente.class,"Error en getStringFromInputStream ");
		} 
                finally 
                {	if (br != null) 
                            try {  br.close();
				} catch (Exception e) 
				{
					Log.log(e,Log.MOD_WEBCRAWLER,Log.LEVEL_ERROR, DescargarFuente.class,"Error en getStringFromInputStream ");					
						
				}
		}
		return sb.toString();
	}
}

